package com.zh.chat.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.zh.chat.util.ConfigUtil;

public class TCPDTO extends DTOBase {
	private static Logger log = Logger.getLogger(TCPDTO.class);

	public TCPDTO(ConfigUtil config) {
		super(config);
		log.info("TcpDTO初始化完成");
	}
	
	public void setClientIP(String ip){
		this.CLIENT_IP = ip;
	}

	public ServerSocket getFreeSocket() {
		int tempPort = TCP_PORT;
		ServerSocket server = null;
		// 找到空闲的TCP连接端口的算法
		boolean flag = true;
		while (flag) {
			try {
				server = new ServerSocket(tempPort);
				flag = false;
			} catch (IOException e) {
				flag = true;
				tempPort += 1;
			}
			if (server != null) {
				System.out.println("找到可用TCP连接端口" + tempPort);
			}
		}
		return server;
	}

	public Socket getClientSocket(ServerSocket server) {
		try {
			// server.setSoTimeout(10000);//设置接收客户端连接的延时
			return server.accept();
		} catch (IOException e) {
			throw new RuntimeException("客户端连接超时");
		}
	}
}